package com.lhyl.front.jcaptcha;

import java.io.PrintWriter;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * MyFormAuthenticationFilter.java
 * <p>Copyright: Copyright (c) 2015 <p> 
 * <p>Company: xinghuo</p>
 *  @author    SeanXiao
 *  @version   1.0
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    	
    	HttpServletRequest httpRequest = (HttpServletRequest) request;  
        HttpServletResponse httpResponse = (HttpServletResponse) response;  
  
        Subject subject = getSubject(request, response);  
  
        if  (null == subject.getPrincipal()) {  
        	
        	// ajax
        	if (isAjax(httpRequest)) 
        	{
            
        		httpResponse.setCharacterEncoding("UTF-8");
        		httpResponse.setStatus(403);
                PrintWriter out = httpResponse.getWriter();
                out.println("{errorcode:403,message:'您尚未登录或登录时间过长,请重新登录!'}");
                
                try
                {
                    out.flush();
                    out.close();
                }
                catch (Exception e)
                {
                    System.err.println(e);
                }
                
                return false;
            }
        }
        else
        {
			
            // ajax
            if (isAjax(httpRequest)) 
            {
            
                httpResponse.setCharacterEncoding("UTF-8");
                httpResponse.setStatus(401);
                PrintWriter out = httpResponse.getWriter();
                out.println("{errorcode:401,message:'您没有足够的权限执行该操作!'}");
                
                try
                {
                    out.flush();
                    out.close();
                }
                catch (Exception e)
                {
                    System.err.println(e);
                }
                
                return false;
            }
        }
    	
        if(request.getAttribute(getFailureKeyAttribute()) != null) {
            return true;
        }
        return super.onAccessDenied(request, response, mappedValue);
    }
    
    /**
     * 覆盖默认实现，用sendRedirect直接跳出框架，以免造成js框架重复加载js出错。
     * @param token
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws Exception  
     * @see org.apache.shiro.web.filter.authc.FormAuthenticationFilter#onLoginSuccess(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.subject.Subject, javax.servlet.ServletRequest, javax.servlet.ServletResponse)
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
            ServletRequest request, ServletResponse response) throws Exception {
        //issueSuccessRedirect(request, response);
        //we handled the success redirect directly, prevent the chain from continuing:
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
         
        if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With")) 
                || request.getParameter("ajax") == null) {// 不是ajax请求
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
        } else {
            httpServletRequest.getRequestDispatcher("/home").forward(httpServletRequest, httpServletResponse);
        }
        
        // 登录成功后干掉验证码
        JCaptcha.captchaService.removeCaptcha(httpServletRequest.getSession().getId());
         
        return false;
    }
    
    private boolean isAjax(HttpServletRequest httpRequest)
    {
        if ("XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With")))
        {
            return true;
        }
        
        return false;
    }
}
